const mongoose = require('mongoose');
const Router = require('koa-router');
const CommentSchema = mongoose.model('CommentSchema');
const UserSchema = mongoose.model('UserSchema');
const CommentRouter = new Router();

CommentRouter.post('/add', async ctx => {
  try {
    const { body } = ctx.request;
    const { openId } = body;
    const user = await UserSchema.findOne({ openId }).exec();
    body.userId = user._id;
    await new CommentSchema(body).save();
    ctx.body = {
      code: 200,
      data: '添加评论成功',
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
})

CommentRouter.get('/getList', async ctx => {
  try {
    const { isbnCode } = ctx.request.query;
    const list = await CommentSchema.find({ isbnCode })
      .populate({
        path: 'userId',
        select: {
          avatarUrl: 1,
          nickName: 1,
          _id: 0,
        }
      })
      .exec();
    ctx.body = {
      code: 200,
      data: list,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
})

// 获取我的评论列表
CommentRouter.get('/getMyComment', async ctx => {
  try {
    const pageSize = 10;
    const { openId, page } = ctx.request.query;
    const skipCount = (page - 1) * pageSize;
    const total = await CommentSchema.find().countDocuments();
    const list = await CommentSchema
    .find({ openId }) // 查询评论列表
    .sort({ createTime: -1 }) // 降序排列
    .skip(skipCount)
    .limit(pageSize)
    .populate({
      path: 'userId',
      select: {
        avatarUrl: 1,
        nickName: 1,
        _id: 0,
      }
    })
    .exec();
    ctx.body = {
      code: 200,
      data: {
        list,
        total,
      },
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
})

module.exports = CommentRouter;